package com.qf.smartdevice.events.listeners;

import com.qf.smartdevice.events.DevicePowerEvent;
import com.qf.smartdevice.pojo.SysDevice;
import com.qf.smartdevice.service.SysDeviceService;
import com.qf.smartdevice.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author 王博康
 * @version 1.0
 * @project devicemanagementsystem
 * @description: TODO
 * @date 2022/3/27 11:50 星期日
 */
@Component
@EnableAsync
public class DevicePowerListener {


    private SysDeviceService deviceService;

    @Autowired
    public void setDeviceService(SysDeviceService deviceService) {
        this.deviceService = deviceService;
    }

    @Async
    @EventListener
    public void onEvent(DevicePowerEvent event){
        //获取事件信息
        String deviceId = event.getDeviceId();
        String ip = event.getIp();
        String location = RequestUtil.getLocationByIp(ip);
        //设置信息
        SysDevice sysDevice = new SysDevice();
        sysDevice.setDeviceId(deviceId);

        //根据设备状态,设置其他信息
        switch (event.getDeviceStatus()){
            case ONLINE:
                sysDevice.setIsOnline(1L);
                sysDevice.setConnectTime(new Date());
                sysDevice.setCurrentConnectIp(ip);
                sysDevice.setConnectLocation(location);

                break;
            case OFFLINE:
                sysDevice.setIsOnline(2L);
                sysDevice.setLostConnectTime(new Date());
                break;
        }
        deviceService.updateDeviceById(sysDevice);

    }
}
